from courses.models import Course
from courses.auth.decorators import required_role
from django.http import HttpResponse
from models import *

import os

#from django.dynamic_media_serve import serve

def do_serve(request, path):
    node = Node(request.course.files, path)
    if node.is_file:
        return do_serve_file(request, node.path)
    elif node.is_dir:
        return do_serve_dir(request, node.path)

def do_serve_file(request, path):
    from dynamic_media_serve import serve
    course = request.course
    
    f = FileNode(path)
    
    return serve(request, f.abspath)
    
def do_serve_files(request, files_list, flat=False, doc_root='', filename=False):
    import tempfile
    from dynamic_media_serve import serve
    
    ZIP_PREFIX = 'betterspace-zip-'
    
    z = tempfile.NamedTemporaryFile(suffix='.zip', prefix=ZIP_PREFIX)
    Node.zip_files(files_list, z, flat=flat, doc_root=doc_root)
    response = serve(request, z.name,
        document_root=tempfile.gettempdir(),
        force_mimetype='application/zip'
    )
    if doc_root:
        filename = os.path.basename(doc_root)
    else:
        filename = 'betterspace-files-%s-%s' % (
            request.course.instructor.user.username, request.course.slug
        )
    
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    #z.close()
    print z.name
    return response
    
def do_serve_dir(request, dir_path):
    files = Directory(dir_path).get_files()
    return do_serve_files(request, files, flat=False, doc_root=dir_path)

def serve_files(request):    
    """
    #ajax view.  Zips together selected files and serves the zip.
    #
    # To serve a whole directory, set "dir_path" in POST to the directory's path
    # relative to the course's document root (c.files.abspath)
    #
    # To serve a list of selected files, set "file_list" in POST to a JSON encoding
    # of a list of filepaths relative to the course's document root (c.files.abspath).
    #
    # For example, if you want to serve file1.txt, dir1/file2.txt, and dir1/dir2/file3.txt, 
    # you'd set "file_list" to:
    #
    # '["file1.txt", "dir1/file2.txt", "dir1/dir2/file3.txt"]'
    #
    """
    import json
    #c = Course.getByNames(name=course_name,instructor=instructor)
    c = request.course
    if request.POST['file_list']:
        return do_serve_files(request, [FileNode(c.files.path, path).abspath for path in json.loads(request.POST['file_list'])], flat=True)
    elif request.POST['dir_path']:
        if request.POST['dir_path'] == '__root__':
            dir_path = ''
        else:
            dir_path = request.POST['dir_path']
        #as a fallback, zip together all the course's files and serve them up.
        return do_serve_dir(request, Directory(c.files.path, dir_path).abspath)
        
    raise KeyError('View serve_files was called without "file_list" or "dir_path" in POST data!')

@required_role('instructor')
def delete_files(request):
    pass #TODO

@required_role('instructor')
def add_files(request):
    pass #TODO
